const app = getApp()
const util = require("../../../utils/util")

Page({
  data: {
    superviseContentList: [],
    accounts: [],
    accountIndex: -1,
    currentIndex: -1
  },
  onLoad: function (options) {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      altitude: true,
      fail: (res) => {
        //不允许打开定位
        wx.hideLoading()
        wx.getSetting({
          success(res) {
            //开启小程序内定位
            if (res.authSetting["scope.userLocation"] == false) {
              wx.showModal({
                content: '请允许小程序使用地理位置功能！您可以在【我的】页面点击【设置】按钮快捷设置。',
                confirmText: "去设置",
                success: res => {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/mine/mine'
                    })
                  }
                }
              })
            } else {
              //开启系统设置定位
              wx.getSystemInfo({
                success: res => {
                  console.log(res)
                  if (res.platform == "ios") {
                    that.setData({
                      locationContent: "请在系统设置-微信里开启允许微信使用地理位置的开关"
                    })
                  }
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                },
                fail: res => {
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                }
              })
            }

          }
        })
      },
      success: res => {
        console.log(res)
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          altitude: res.altitude
        })
      }
    })
    this.getSuperviseContent()
    this.getCategoryList()
  },

  // onShow: function () {
  //   this.getSuperviseContent()
  // },


  inputContent: function (e) {
    e.detail.value = app.trim(e.detail.value)
    let index = parseInt(e.target.id.split('-')[1]),
      superviseContentList = this.data.superviseContentList
    superviseContentList[index].contentLength = parseInt(e.detail.value.length)
    superviseContentList[index].recordContent = e.detail.value
    this.setData({
      superviseContentList: superviseContentList
    })
  },

  switchChange: function (e) {
    console.log("e", e)
    let contentIndex = parseInt(e.currentTarget.id.split('-')[1])
    let superviseContentList = this.data.superviseContentList
    if (e.currentTarget.dataset.value == false) {
      superviseContentList[contentIndex].normal = -1
      superviseContentList[contentIndex].contentLength = 0
      superviseContentList[contentIndex].dealFiles = []
      superviseContentList[contentIndex].imageUrl = []
      superviseContentList[contentIndex].hide = false
      superviseContentList[contentIndex].imageNum = 0
      superviseContentList[contentIndex].recordContent = ""
      superviseContentList[contentIndex].video = ""
      superviseContentList[contentIndex].videoSrc = ""
      superviseContentList[contentIndex].selectedIndex = null
      superviseContentList[contentIndex].modalComfirm = null
      superviseContentList[contentIndex].modalName = null
      superviseContentList[contentIndex].waringInfo = ""
    } else {
      superviseContentList[contentIndex].normal = 0
      superviseContentList[contentIndex].recordContent = ""
      superviseContentList[contentIndex].video = ""
      superviseContentList[contentIndex].videoSrc = ""
      superviseContentList[contentIndex].selectedIndex = null
      superviseContentList[contentIndex].modalComfirm = null
      superviseContentList[contentIndex].modalName = null
      superviseContentList[contentIndex].waringInfo = ""
    }
    this.setData({
      superviseContentList: superviseContentList,
    })
  },

  getSuperviseContent() {
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getSuperviseContentById',
      method: "GET",
      data: {
        id: app.globalData.superviseId,
        schoolId: app.globalData.superviseSchoolId,
        userId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
        this.setData({
          superviseContentList: res.data
        })
      }
    })
  },

  submit: util.throttle(function (e) {
    let index = e.currentTarget.dataset.index
    let normal = this.data.superviseContentList[index].normal == 0 ? 1 : 2
    let photoOrVideo
    if (normal == 2) {
      let waringInfoStr = 'superviseContentList[' + index + '].waringInfo'
      this.setData({
        [waringInfoStr]: ""
      })
      if (this.data.superviseContentList[index].selectedIndex == null) {
        this.setData({
          [waringInfoStr]: "请选择隐患类型"
        })
      } else if (this.data.superviseContentList[index].recordContent == "" || !this.data.superviseContentList[index].recordContent) {
        this.setData({
          [waringInfoStr]: "请输入详细问题"
        })
      } else if (this.data.superviseContentList[index].imageUrl == null || this.data.superviseContentList[index].imageUrl.length == 0) {
        this.setData({
          [waringInfoStr]: "请上传照片"
        })
      }
      if (this.data.superviseContentList[index].waringInfo != "") {
        wx.showToast({
          title: this.data.superviseContentList[index].waringInfo,
          image: "/images/warning.png"
        })
        return
      }
    }


    let superviseContent = e.currentTarget.dataset.supervisecontent
    let categoryId = this.data.categoryId[this.data.superviseContentList[index].selectedIndex]
    let createTime = util.formatTime(new Date())
    let modifyTime = util.formatTime(new Date())
    let superviseContentId = e.currentTarget.dataset.supervisecontentid
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/submitSupervise',
      method: 'POST',
      data: {
        userId: app.globalData.userId,
        superviseRelationId: app.globalData.superviseId,
        normal: normal,
        superviseContent: superviseContent,
        createTime: createTime,
        modifyTime: modifyTime,
        superviseContentId: superviseContentId
      },
      dataType: 'json',
      success: res => {
        if (res.data.res == "success") {
          let superviseContentListStr = 'superviseContentList[' + index + '].normal'
          this.setData({
            [superviseContentListStr]: normal
          })
          if (normal == 1) {
            wx.showToast({
              title: '提交成功',
              icon: 'success'
            })
          } else if (normal == 2) {
            wx.request({
              url: app.inspectUrl + '/WeChat/weChatSystem/safetyReport',
              method: 'POST',
              data: {
                schoolId: app.globalData.superviseSchoolId,
                safetyLevel: 2,
                address: app.globalData.superviseSchoolName,
                content: this.data.superviseContentList[index].recordContent,
                photo: this.data.superviseContentList[index].imageUrl.join(","),
                video: this.data.superviseContentList[index].video,
                reporter: app.globalData.userId,
                categoryId: categoryId,
                inspectConditionId: -1,
                superviseId: res.data.id,
                latitude: this.data.latitude,
                longitude: this.data.longitude,
                altitude: this.data.altitude
              },
              dataType: 'json',
              success: res => {
                if (res.data.res == "success") {
                  let safetySceneId = res.data.data
                  wx.request({
                    url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
                    method: 'GET',
                    dataType: 'json',
                    success: res => {
                      console.log("res", res)
                      let access_token = res.data.access_token
                      wx.request({
                        url: app.inspectUrl + '/WeChat/weChatSystem/getChargeManWeChatId',
                        method: 'POST',
                        data: {
                          categoryId: categoryId,
                          schoolId: app.globalData.superviseSchoolId
                        },
                        dataType: 'json',
                        success: res => {

                          let unbind = []
                          for (let i = 0; i < res.data.length; i++) {
                            if (res.data[i].res == "success") {
                              let datetime = util.formatTime(new Date())
                              wx.request({
                                url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                                data: {
                                  template: 1,
                                  accessToken: access_token,
                                  touser: res.data[i].msg,
                                  safetySceneId: safetySceneId,
                                  data: {
                                    first: {
                                      value: "【巡查异常】"
                                    },
                                    keyword1: {
                                      value: app.globalData.realname
                                    },
                                    keyword2: {
                                      value: datetime
                                    },
                                    keyword3: {
                                      value: `巡查时发现异常，请及时查看!`
                                    }
                                  }
                                },
                                method: 'POST',
                                dataType: 'json'
                              })
                            } else {
                              unbind.push(res.data[i].msg)
                            }
                          }
                        }
                      })
                    }
                  })
                } else {
                  wx.showToast({
                    title: '上报失败',
                    image: "/images/error.png"
                  })
                }
              },
              fail: res => {
                wx.showToast({
                  title: '网络异常！',
                  image: '/images/warning.png'
                })
              }
            })
          }

        }
      },
      complete: () => {
        wx.hideLoading()
      }
    })


  }, 1000),


  getCategoryList: function () {
    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/getAllValidInspectItems',
      method: 'POST',
      data: {
        schoolId: app.globalData.superviseSchoolId
      },
      dataType: 'json',
      success: res => {
        let accounts = [],
          categoryId = []
        for (let i = 0; i < res.data.length; i++) {
          accounts.push({
            item: res.data[i].category,
            checked: false
          })
          categoryId.push(res.data[i].categoryId)
        }
        this.setData({
          accounts: accounts,
          categoryId: categoryId
        })
      },
      fail: res => {
        wx.showToast({
          title: '网络异常！',
          image: '/images/warning.png'
        })
      }
    })
  },

  showModal(e) {
    let currentIndex = e.currentTarget.dataset.index
    this.setData({
      currentIndex: currentIndex
    })
    let accounts = this.data.accounts.map((item, index) => {
      return {
        item: item.item,
        checked: index == this.data.superviseContentList[currentIndex].selectedIndex ? true : false
      }
    })
    let modalComfirmStr = "superviseContentList[" + currentIndex + "].modalComfirm"
    let modalNameStr = "superviseContentList[" + currentIndex + "].modalName"
    this.setData({
      [modalNameStr]: "RadioModal",
      accounts: accounts,
      [modalComfirmStr]: this.data.superviseContentList[currentIndex].selectedIndex != null ? true : false,
      // forwardId: e.currentTarget.dataset.id
    })
  },

  hideModal(e) {
    let modalNameStr = "superviseContentList[" + this.data.currentIndex + "].modalName"
    this.setData({
      [modalNameStr]: null
    })
  },

  radioSelect(e) {

    let radioIndex = e.currentTarget.dataset.index,
      accounts = this.data.accounts.map((item, index) => {
        return {
          item: item.item,
          checked: index == radioIndex ? true : false
        }
      }),
      status
    let selectedIndexStr = "superviseContentList[" + this.data.currentIndex + "].selectedIndex"
    let modalComfirmStr = "superviseContentList[" + this.data.currentIndex + "].modalComfirm"
    this.setData({
      accounts: accounts,
      [selectedIndexStr]: radioIndex
    })
    if (this.data.superviseContentList[this.data.currentIndex].selectedIndex != null) status = true
    else status = false
    this.setData({
      [modalComfirmStr]: status
    })
  },

  confirmSelect(e) {
    let modalNameStr = "superviseContentList[" + this.data.currentIndex + "].modalName"
    this.setData({
      // accountIndex: this.data.selectedIndex,
      [modalNameStr]: null
    })
  },

  // 照片
  previewImageDeal: function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let current = e.currentTarget.id.split('-')[2]
    let superviseContent = this.data.superviseContentList[itemIndex]
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: superviseContent.dealFiles // 需要预览的图片http链接列表
    })
  },

  //自定义相机组件
  toCamera: function (e) {
    const index = e.currentTarget.dataset.index
    let category
    let waringInfoStr = 'superviseContentList[' + index + '].waringInfo'
    this.setData({
      [waringInfoStr]: ""
    })
    if (this.data.superviseContentList[index].selectedIndex == null) {
      this.setData({
        [waringInfoStr]: "请选择隐患类型"
      })
    } else if (this.data.superviseContentList[index].recordContent == "" || !this.data.superviseContentList[index].recordContent) {
      this.setData({
        [waringInfoStr]: "请输入详细问题"
      })
    }
    if (this.data.superviseContentList[index].waringInfo != "") {
      wx.showToast({
        title: this.data.superviseContentList[index].waringInfo,
        image: "/images/warning.png"
      })
    } else {
      wx.navigateTo({
        url: '../../../subpages/pages/cameraIdentified/cameraIdentified?address=' + app.globalData.superviseSchoolName + '&recordContent=' +
          this.data.superviseContentList[index].recordContent + '&type=6' + '&level=一般' + '&category=' + this.data.accounts[this.data.superviseContentList[index].selectedIndex].item + '&contentIndex=' + index
      })
    }
  },

  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showLoading({
          title: "图片上传中",
          mask: true
        })

        let tempImg = res.tempFilePaths
        for (let i = 0; i < tempImg.length; i++) {
          wx.uploadFile({
            url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload',
            filePath: res.tempFilePaths[i],
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              if (res.data == "fail") {
                wx.showToast({
                  title: "图片上传失败",
                  image: "/images/error.png"
                })
              } else {
                wx.showToast({
                  title: "上传成功"
                })
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
                let superviseContentList = that.data.superviseContentList
                superviseContentList[itemIndex].dealFiles.push(tempImg[i])
                superviseContentList[itemIndex].imageUrl.push(res.data)
                superviseContentList[itemIndex].imageNum++
                that.setData({
                  superviseContentList: superviseContentList
                })
                if (that.data.superviseContentList[itemIndex].dealFiles.length == 3) {
                  superviseContentList[itemIndex].hide = true
                  that.setData({
                    superviseContentList: superviseContentList
                  })
                }
              }
            },
            fail: res => {
              wx.showToast({
                title: "图片上传失败",
                image: "/images/error.png"
              })
            }
          })
        }

      }
    })
  },

  deleteImage: function (e) {
    let that = this
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let imgIndex = parseInt(e.currentTarget.id.split('-')[2])
    let superviseContent = this.data.superviseContentList[itemIndex]
    let target = superviseContent.imageUrl[imgIndex]
    let dealFilesStr = "superviseContentList[" + itemIndex + "].dealFiles"
    let imageUrlStr = "superviseContentList[" + itemIndex + "].imageUrl"
    let imageNumStr = "superviseContentList[" + itemIndex + "].imageNum"
    let hideStr = "superviseContentList[" + itemIndex + "].hide"
    let temp = []
    let tempUrl = []
    let dealFilesLength = superviseContent.dealFiles.length
    for (let i = 0; i < dealFilesLength; i++) {
      if (i != imgIndex) {
        temp.push(superviseContent.dealFiles[i])
        tempUrl.push(superviseContent.imageUrl[i])
      }
    }

    wx.showActionSheet({
      itemList: ['删除这张照片'],
      success: res => {
        if (!res.cancel) {
          that.setData({
            [dealFilesStr]: temp,
            [imageUrlStr]: tempUrl
          })
          wx.setStorageSync('fileAndImg-' + itemIndex, {
            dealFiles: temp,
            imageUrl: tempUrl,
          })
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteFile',
            method: 'POST',
            data: {
              filename: target.split("image/")[1]
            },
            dataType: 'json',
            success: res => {
              let imageNum = superviseContent.imageNum - 1
              that.setData({
                [imageNumStr]: imageNum,
              })
              if (dealFilesLength == 3) {
                that.setData({
                  [hideStr]: false
                })
              }
            }
          })
        }
      }
    })
  },

  //视频
  press: function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let superviseContentList = this.data.superviseContentList
    wx.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      camera: 'back',
      success: res => {
        if (res.size > 2097152) {
          wx.showToast({
            title: '文件大于2M！',
            mask: true,
            image: "/images/error.png"
          })
        } else {
          wx.uploadFile({
            url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload2',
            filePath: res.tempFilePath,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              console.log(res.data)
              superviseContentList[itemIndex].video = res.data
              superviseContentList[itemIndex].videoSrc = app.imageUrl + res.data
              this.setData({
                superviseContentList: superviseContentList
              })
            }
          })
        }
      },
      fail(res) {
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo: function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let superviseContentList = this.data.superviseContentList
    let target = superviseContentList[itemIndex].video
    wx.showActionSheet({
      itemList: ['删除视频'],
      success: res => {
        if (!res.cancel) {
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteVideo',
            method: 'POST',
            data: {
              filename: target.split("video/")[1]
            },
            dataType: 'json',
            success: res => {
              if (res.data == "success") {
                superviseContentList[itemIndex].video = ""
                superviseContentList[itemIndex].videoSrc = ""
                this.setData({
                  superviseContentList: superviseContentList
                })
              }
            }
          })
        }
      }
    })
  }

})